import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, TextInput, ScrollView, KeyboardAvoidingView, Platform, Keyboard
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { SelectComponent } from '../_components/SelectComponent';
import { Common } from '../../../../component/common/Common.js';
import ToastUtil from '../../../../utils/toast';
import DateGapPicker from '../../../../components/common/DateGapPicker';
import { TitleView } from '../_components/TitleView.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http'
import Dictionary from '../../../../utils/dictionary';
const scale = GLOBAL.SCALE;

let sendData = {
	planRemark: '',//简要分析
};
export class IntentionAddPage extends Component {
	static navigationOptions = {
		header: null
	}

	requesting;

	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		this.productList = params.productList || [];
		this.totalFeeAmt = params.totalFeeAmt || 0;
		this.intentionList = params.intentionList || [];
		this.intentionItem = params.intentionItem;
		this.sellQuantity = '';
		this.selectIndex = '-1';
		this.state = {
			openDatePicker: false,
			currDateKey: '',
			date: {
				startDate: '',
				endDate: ''
			},

			contractPrice: '', // 暂定价/暂定价
			canSellNumber: 0, // 商品可售数量

			collectionModal: false,
			collectionData: [],
			collectionValue: '',
			collectionIndex: -1,
			planRecvType: '', // 拟收款类型

			extId: '', // 编辑时需传
			orderId: params.orderId,
			itemId: '',
			companyId: '', // 销售客户
			companyName: '',
			planSellBeginDate: '',  // 开始时间
			planSellEndDate: '',   // 结束时间
			goodsId: '',
			goodsName: '',
			planSellPrice: '', // 拟销售价格
			planSellQuantity: '', // 拟销售数量
			planFinanceCost: '',//预计财务费用
			planLogisticsCost: '',//预计物流费用
			companyAddressId: '', // 客户收货地址id
			companyAddressName: '', // 客户收货地址
			planGrossProfit: 0, // 预计毛利

			status: 'data',   // 状态 
		}
	}
	componentWillMount () {
		this._collectionFn();  // 收款类型 - 数据字典
		this._getProductListInfo();
		this._initEditData(this.props.navigation.state.params.intentionItem);
	}

	componentWillUnmount () {
		sendData.planRemark = '';
	}

	// 如果step2只选了一个商品，需要将商品、数量、单价自动填入
	_getProductListInfo = () => {
		if (this.productList && this.productList.length == 1) {
			let { goodsId, goodsName, itemId, price, quantity } = this.productList[0];
			this.sellQuantity = quantity;
			this.setState({
				goodsId, goodsName, itemId, planSellPrice: price, contractPrice: price, planSellQuantity: quantity
			}, () => {
				this._calculateQuantity(quantity, !this.intentionItem.extId);
				this._calculateProfit(); // 计算毛利
			})
		}
	}

	// 计算可售量
	_calculateQuantity = (quantity, editQuantity) => {
		let { canSellNumber } = this.state;
		let usedQuantity = 0; // 历史意向的销售数量总和
		if (this.intentionList.length > 0) {
			// 判断是否是新增
			if (this.intentionItem && this.intentionItem.extId) {
				canSellNumber = 0
				this.intentionList.forEach((v, i) => {
					if (this.intentionItem.extId != v.extId) {
						usedQuantity += v.planSellQuantity
					}
				})
			} else {
				this.intentionList.forEach((v, i) => {
					usedQuantity += v.planSellQuantity
				})
			}
		}
		canSellNumber = quantity - usedQuantity;
		// 如果是编辑，首次进入不需要更改数量
		if (editQuantity) {
			this.setState({
				canSellNumber,
				planSellQuantity: canSellNumber
			})
		} else {
			this.setState({
				canSellNumber
			})
		}


	}

	//初始化编辑数据
	_initEditData (intentionItem) {
		if (intentionItem && intentionItem.itemId) {
			let { extId, itemId, companyId, companyName, goodsId, goodsName, planSellQuantity, planSellPrice, planSellBeginDate, planSellEndDate, planRecvType, planRecvTypeName, companyAddressId, companyAddressName, planFinanceCost, planLogisticsCost, planRemark } = intentionItem
			sendData.planRemark = planRemark;
			this.setState({
				extId, itemId, companyId, companyName, goodsId, goodsName, planSellQuantity, planSellPrice, date: { startDate: planSellBeginDate, endDate: planSellEndDate }, planRecvType, collectionValue: planRecvTypeName, companyAddressId, companyAddressName, planFinanceCost: planFinanceCost || '', planLogisticsCost: planLogisticsCost || '',
			})
		}
	}

	// 选择销售客户
	_providerFn = () => {
		let { companyId } = this.props.navigation.state.params
		this.props.navigation.navigate('SeachSupplierPage', {
			orderType: sendData.orderType,
			type: 'IntentionAddPage',
			queryType: 'ORDER_ADD',
			companyIdBuy: companyId,
			callBack: selectData => {
				let { companyName, companyId } = selectData
				this.setState({
					companyName,
					companyId
				})
			}
		});
	}

	//选择商品
	_goGoodsList = () => {
		this.props.navigation.navigate('ProductSelectPage', {
			pushIndex: this.selectIndex,
			orderId: this.state.orderId,
			goodsId: this.state.goodsId,
			type: 'INTENTION',
			callBack: (data, index) => {
				this.sellQuantity = data.quantity;
				this.selectIndex = index;
				this.setState({
					goodsId: data.goodsId,
					goodsName: data.goodsName,
					itemId: data.itemId,
					planSellQuantity: data.quantity,
					planSellPrice: data.price,
					contractPrice: data.price
				}, () => {
					this._calculateQuantity(data.quantity, true);
					this._calculateProfit();
				})
			}
		})
	}

	//打开模态框
	_selecOpen = (obj) => {
		for (key in obj) {
			obj[key] = true;
		}
		this.setState(obj);
	}
	//查找字符串中的数字  并且返回数组
	_getNumberFn = (str) => {
		if (!str) return;
		var numberArr = [];
		var newStr = str.replace(/\d+/g, function () {
			numberArr.push(arguments[0]);
		});
		return numberArr.join('-');
	}

	//保存
	async _save () {
		if (this.requesting) return;
		Keyboard.dismiss();
		let subData = {
			orderRptExtList: []
		};

		let {
			contractPrice, canSellNumber, extId, orderId, itemId, companyId, goodsId, goodsName, planSellQuantity, planSellPrice, planRecvType, date, companyAddressId, planFinanceCost, planLogisticsCost, planGrossProfit
		} = this.state

		let { planRemark } = sendData;

		subData.orderRptExtList[0] = {
			extId, orderId, itemId, companyId, goodsId, goodsName: goodsName || '', planSellQuantity, planSellPrice, planSellBeginDate: date.startDate, planSellEndDate: date.endDate, planRecvType, companyAddressId, planFinanceCost: planFinanceCost || '', planLogisticsCost: planLogisticsCost || '', planRemark, planGrossProfit
		};
		if (!companyId) {
			ToastUtil.showWarning('请选择销售客户');
			return false;
		}
		if (!goodsId) {
			ToastUtil.showWarning('请选择销售商品');
			return false;
		}
		if (!planSellQuantity) {
			ToastUtil.showWarning('请填写销售数量');
			return false;
		}
		if (planSellQuantity == 0) {
			ToastUtil.showWarning('销售数量不能为0');
			return false;
		}
		if (planSellQuantity > canSellNumber) {
			ToastUtil.showWarning(`剩余可销售数量${canSellNumber}吨`);
			return false;
		}
		if (!planSellPrice) {
			ToastUtil.showWarning('请填写销售单价');
			return false;
		}
		if (planSellPrice <= contractPrice) {
			ToastUtil.showWarning(`销售单价必须大于${contractPrice}元/吨`);
			return false;
		}
		if (!date.startDate || !date.endDate) {
			ToastUtil.showWarning('请填写销售时间');
			return false;
		}
		if (!planRecvType) {
			ToastUtil.showWarning('请选择收款类型');
			return false;
		}
		if (!companyAddressId) {
			ToastUtil.showWarning('请选择客户收货地址');
			return false;
		}
		this.setState({
			status: 'loading'
		})
		this.requesting = true;
		let saveData = await HTTP.POST(API_GENERATE(API.POTENTIAL_CLIENTS_ADD), subData);
		this.setState({
			status: 'data'
		})
		if (saveData) {
			ToastUtil.showSuccess('意向新增成功').then(() => {
				this.requesting = false;
				this.props.navigation.state.params.callBack('data')
				this._headCloes();
			})
		} else {
			this.requesting = false;
		}
	}

	//列表 选中一个收款类型  - 且关闭模态框
	_collectionCallBack = (index) => {
		this.setState({
			collectionModal: false,
			collectionValue: this.state.collectionData[index].dictName,
			planRecvType: this.state.collectionData[index].dictKey,
			collectionIndex: index
		})
	}

	//数据字典-付款方式
	_collectionFn = async () => {
		let data = await Dictionary.get('EC_PAY_TYPE')
		this.setState({
			collectionData: data
		})
	}

	// 获取客户收货地址
	_getAddress = () => {
		let { companyId, companyName } = this.state
		if (companyId && companyName) {
			this.props.navigation.navigate('DeliveryAddress', {
				companyId,
				companyName,
				getAddressCallBack: (data) => {
					if (data.length) {
						let address = data[0];
						this.setState({
							companyAddressName: (address.provinceName ? address.provinceName + ' ' : '') + (address.cityName ? address.cityName + ' ' : '') + (address.areaName ? address.areaName : '') + ' ' + (address.addressName ? address.addressName : address.detailAddress),
							companyAddressId: address.addrId,
						})
					};
				}
			});
		} else {
			ToastUtil.showWarning('请先选择销售客户')
		}

	}

	// 预测本单毛利
	_calculateProfit = () => {
		// 拟销售单价*拟销售数量-物流费用-财务费用 - 拟销售数量*(采购暂定价 或 一口价)-预算费用估算
		let { planSellPrice, planSellQuantity, planFinanceCost, planLogisticsCost } = this.state

		if (planSellPrice && planSellQuantity) {
			let totalFeeAmt = this.totalFeeAmt;
			let contractPrice = this.state.contractPrice;
			// 销售数量和拟销售数量比较，谁小用谁计算
			let quantity = this.sellQuantity > planSellQuantity ? planSellQuantity : this.sellQuantity;
			let planGrossProfit = planSellPrice * quantity - planFinanceCost - planLogisticsCost - quantity * contractPrice - totalFeeAmt;
			this.setState({
				planGrossProfit
			})
		} else {
			this.setState({
				planGrossProfit: 0
			})
		}

	}

	// 关闭弹框
	_closeModal = (obj) => {
		for (key in obj) {
			obj[key] = false;
		}
		this.setState(obj);
	}

	_headCloes = () => {
		this.props.navigation.goBack();
	}
	render () {
		let { collectionModal, collectionValue, collectionData, collectionIndex,
			goodsName, planSellPrice,
			companyAddressName, companyAddressId, status,
			planLogisticsCost, planFinanceCost, planRecvType, companyName, planSellQuantity, planGrossProfit } = this.state;
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<ScrollView style={{
					paddingLeft: 15 * scale,
					paddingRight: 15 * scale
				}} keyboardShouldPersistTaps={'handled'}>
					<Common type="headCloes" callBack={this._headCloes} />
					<TitleView title={'意向客户'} describe={'拟销售客户信息'} />
					<View style={{ paddingTop: 15 * scale }}>
						<SelectComponent callBack={() => { this._providerFn() }} name={'拟销售客户'} value={companyName || '请选择'} />
						<SelectComponent name={'拟销售商品'} value={goodsName || '请选择'} callBack={() => { this._goGoodsList() }} />
						<SelectComponent rightText={'吨'} type="input" name={'拟销售数量'} keyboardType={'numeric'} value={(planSellQuantity) + ''} inputFn={(text) => {
							this.setState({ planSellQuantity: text }, () => {
								this._calculateProfit()
							})
						}} />
						<SelectComponent icon="￥" rightText={'元/吨'} type="input" keyboardType={'numeric'} name={'拟销售单价'} value={(planSellPrice || '') + ''} inputFn={(text) => {
							this.setState({ planSellPrice: text }, () => {
								this._calculateProfit()
							})
						}} />

						<SelectComponent name={'拟销售时间'} value={this.state.date.startDate + ' 至 ' + this.state.date.endDate}
							callBack={() => {
								Keyboard.dismiss();
								this.setState({ openDatePicker: true, currDateKey: 'date' })
							}} />

						<SelectComponent name={'拟收款类型'} value={planRecvType ? (collectionValue + '') : '请选择'} callBack={() => { this._selecOpen({ collectionModal }) }} />
						<SelectComponent callBack={() => { this._getAddress() }} name={'拟客户收货地址'} value={companyAddressId ? companyAddressName : '请选择'} />
						<View style={styles.listItem}>
							<View style={styles.boxAll}>
								<Text style={styles.boxItemName}>物流费用</Text>
								<View style={styles.boxItem}>
									<Text style={styles.boxItemValue}>￥</Text>
									<TextInput
										ref="accountInput"
										keyboardType={'numeric'}
										style={styles.listInput}
										underlineColorAndroid='transparent'
										placeholderTextColor="#BFBFBF"
										maxLength={30}
										defaultValue={(planLogisticsCost) + ''}
										onChangeText={(text) => {
											const newText = text.replace(/[^\d]+/, '');
											this.setState({ planLogisticsCost: newText }, () => {
												this._calculateProfit()
											})
										}}
									/>
								</View>
							</View>

							<View style={styles.boxAll}>
								<Text style={styles.boxItemName}>财务费用</Text>
								<View style={styles.boxItem}>
									<Text style={styles.boxItemValue}>￥</Text>
									<TextInput
										ref="accountInput"
										keyboardType={'numeric'}
										style={styles.listInput}
										underlineColorAndroid='transparent'
										placeholderTextColor="#BFBFBF"
										defaultValue={(planFinanceCost) + ''}
										maxLength={30}
										onChangeText={(text) => {
											const newText = text.replace(/[^\d]+/, '');
											this.setState({ planFinanceCost: newText }, () => {
												this._calculateProfit()
											})
										}}
									/>
								</View>
							</View>
						</View>
						<SelectComponent type="input" name={'资源平衡(客户需求)及市场简要分析'} maxLength={150} value={sendData.planRemark + ''} inputFn={(text) => {
							sendData.planRemark = text
						}} />
						<View style={styles.profitWrap}>
							<Text style={styles.profitText}>预测本单毛利：￥{planGrossProfit}</Text>
						</View>
						<View style={{ height: 44 * scale }}></View>
					</View>

					<View style={{ width: '100%', height: 60 * scale, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
						<TouchableOpacity onPress={() => { this._save() }} style={[styles.btnSave, styles.mtp9]}>
							<Text style={styles.btnSaveText}>保存</Text>
						</TouchableOpacity>
					</View>
				</ScrollView>

				{
					status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}

				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={collectionIndex} title="选择收款类型" listData={collectionData} selectCallBack={this._collectionCallBack} />
				)} isVisible={collectionModal} closeCallballFn={() => { this._closeModal({ collectionModal }) }} />

				<DateGapPicker
					isVisible={this.state.openDatePicker}
					date={this.state[this.state.currDateKey]}
					cb={(newDate) => {
						this.setState({ openDatePicker: false })
						if (!newDate) return;
						this.setState({
							[this.state.currDateKey]: {
								startDate: newDate.startDate,
								endDate: newDate.endDate
							}
						})

					}}></DateGapPicker>
			</KeyboardAvoidingView >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	listItem: {
		flexDirection: 'row',
		flex: 1,
		alignItems: 'center',
		justifyContent: 'space-between',
	},
	listText: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		height: 17 * scale,
		lineHeight: 17 * scale,
		marginTop: 17 * scale
	},
	boxItem: {
		flexDirection: 'row',
		alignItems: 'center',
		width: 158 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	boxItemName: {
		lineHeight: 40 * scale,
		color: style.color.darkGray,
		marginRight: 3 * scale
	},
	boxItemValue: {
		lineHeight: 40 * scale,
		color: style.color.dark,
	},
	listInput: {
		width: 120 * scale,
	},
	btnSaveText: {
		color: style.color.white,
		fontSize: 18 * scale,
		lineHeight: 44 * scale,
		textAlign: 'center',
	},
	btnSave: {
		width: 345 * scale,
		height: 44 * scale,
		backgroundColor: style.color.themeColor,
		borderRadius: 22 * scale,
		position: 'absolute',
		bottom: 0
	},
	mtp9: {
		marginTop: 9 * scale,
		marginBottom: 49 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	profitWrap: {
		backgroundColor: '#FFEDA7',
		paddingLeft: 13 * scale,
		marginTop: 11 * scale
	},
	profitText: {
		height: 34 * scale,
		lineHeight: 34 * scale,
		fontSize: 12 * scale,
		color: '#C67300',
	}
})